package com.serkol.wx.service.impl;

import cn.binarywang.wx.miniapp.api.WxMaMsgService;
import cn.binarywang.wx.miniapp.api.WxMaService;
import cn.binarywang.wx.miniapp.bean.WxMaSubscribeMessage;
import cn.binarywang.wx.miniapp.bean.WxMaTemplateData;
import cn.binarywang.wx.miniapp.config.WxMaConfig;
import com.serkol.wx.bean.AgentSuccessMsg;
import com.serkol.wx.service.WechatMiniMessageService;
import me.chanjar.weixin.common.error.WxErrorException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

@Service
public class WechatMiniMessageServiceImpl implements WechatMiniMessageService {
    @Autowired
    private WxMaService wxMaService;

    @Override
    public boolean sendMessage( AgentSuccessMsg msg) throws WxErrorException {
        String templateId="6Nceyy_tg970q3H1JVToEXx_H41pRdiElyLZG7NxtcE";
         WxMaConfig wxMaConfig = wxMaService.getWxMaConfig();
        WxMaMsgService msgService = wxMaService.getMsgService();
        WxMaSubscribeMessage uniformMessage = new WxMaSubscribeMessage();

        Map<String, Object> map = new HashMap<>();
        map.put("thing1", msg.getName());
        map.put("thing2", msg.getGoodsName());
        map.put("amount3", msg.getRetailPrice()+"");
        map.put("amount4", msg.getSupplyPrice()+"");
        map.put("amount5", msg.getAgentCommission()+"");
        System.out.println("APPID:"+wxMaConfig.getAppid());

    List<WxMaSubscribeMessage.MsgData> wxMaSubscribeMessageList=new ArrayList<>();
        for(Entry entry : map.entrySet()){

            String mapKey = (String) entry.getKey();

            String mapValue = (String) entry.getValue();

            System.out.println(mapKey+":"+mapValue);
            WxMaSubscribeMessage.MsgData msgData=new WxMaSubscribeMessage.MsgData(mapKey,mapValue);
            wxMaSubscribeMessageList.add(msgData);

        }

uniformMessage.setToUser("oyE6E5GfoBOYSgETeZEWJNPRjCaw");
        List<WxMaTemplateData> data = pareseData(map);
        uniformMessage.setData(wxMaSubscribeMessageList);
        uniformMessage.setTemplateId(templateId);
        msgService.sendSubscribeMsg(uniformMessage);

        return false;
    }

    private List<WxMaTemplateData> pareseData(Map<String, Object> map) {
        List<WxMaTemplateData> datas = new ArrayList<>();
        for (Entry entry : map.entrySet()) {
            WxMaTemplateData data = new WxMaTemplateData();
            String mapKey = (String) entry.getKey();

            Object mapValue = entry.getValue();

            System.out.println(mapKey + ":" + mapValue);
            data.setName(mapKey);
            data.setValue(mapValue + "");
            datas.add(data);

        }
        return datas;
    }
}
